//
//  HYAutoIMG.m
//  HaiYue
//
//  Created by skyline on 2018/5/22.
//  Copyright © 2018年 skyline. All rights reserved.
//

#import "HYAutoIMG.h"
@interface HYAutoIMG ()
@property (nonatomic, strong) HYImageView *img;
@property (nonatomic, strong) UIView *view;
@end
@implementation HYAutoIMG
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        self.backgroundColor = [UIColor clearColor];
        self.view.hidden = NO;
    }
    return self;
}

- (UIView *)view
{
    if (!_view)
    {
        _view = [[UIView alloc] init];
        _view.backgroundColor  = [UIColor blackColor];
        _view.alpha = 0.5;
        [self addSubview:_view];
        [_view mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_offset(UIEdgeInsetsZero);
        }];
    }
    return _view;
}


- (HYImageView *)img
{
    if (!_img)
    {
        _img = [[HYImageView alloc] init];
        _img.image = self.image;
        CGSize size = [_img getFixSizeWithSize:self.bounds.size];
        _img.bounds = CGRectMake(0, 0, size.width, size.height);
        [self addSubview:_img];
        [_img mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self);
            make.centerY.equalTo(self);
            make.size.mas_equalTo(self.img.bounds.size);
        }];
    }
    return _img;
}

- (void)setImage:(UIImage *)image
{
    if (_image != image)
    {
        _image = image;
        self.img.hidden = NO;
    }
}

- (void)setImageURL:(NSString *)imageURL
{
    if (_imageURL != imageURL)
    {
        _imageURL = imageURL;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:self.imageURL]];
            dispatch_async(dispatch_get_main_queue(), ^{
                self.image = [UIImage imageWithData:data];
            });
        });
    }
}

- (HYAutoIMG *)copy
{
    NSData * tempArchive = [NSKeyedArchiver archivedDataWithRootObject:self];
    return [NSKeyedUnarchiver unarchiveObjectWithData:tempArchive];
}

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [super touchesEnded:touches withEvent:event];
    [self sendActionsForControlEvents:UIControlEventTouchUpInside];
}

/*
 // Only override drawRect: if you perform custom drawing.
 // An empty implementation adversely affects performance during animation.
 - (void)drawRect:(CGRect)rect {
 // Drawing code
 }
 */

@end
